package com.chenhao.generator.controller;

import com.chenhao.generator.constant.DriverClassEnum;
import com.chenhao.generator.constant.TemplateEnum;
import com.chenhao.generator.controller.dto.GeneratorParamDto;
import com.chenhao.generator.controller.dto.TableParamDto;
import com.chenhao.generator.entity.GeneratorParam;
import com.chenhao.generator.util.Creator;
import com.chenhao.generator.util.DBUtil;
import com.chenhao.generator.util.ZipUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码逆向生成入口控制器
 *
 * @author:chenHao
 * @version:1.0
 * @since:1.0
 * @createTime:2019-10-02
 */
@Controller
public class GeneratorController {
    public static final Logger logger = LoggerFactory.getLogger(GeneratorController.class);


    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/code")
    public String code() {
        return "code";
    }

    @PostMapping(value = "/toGenerator", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public Map<String, Object> toGenerator(@Valid @RequestBody GeneratorParamDto generatorParamDto) {
        Map<String, Object> resultMap = new HashMap<>();
        logger.info("请求参数" + generatorParamDto.toString());
        try {
            // 代码生成参数
            GeneratorParam generatorParam = new GeneratorParam();
            BeanUtils.copyProperties(generatorParamDto, generatorParam);
            String templateFilePath = TemplateEnum.getFilePath(generatorParamDto.getTemplateCode());
            if (templateFilePath == null) {
                resultMap.put("error", "模板不存在");
                return resultMap;
            }
            // 设置数据库
            String driverClassName = DriverClassEnum.getDriverClassName(generatorParamDto.getDbCode());
            if (StringUtils.isBlank(driverClassName)) {
                resultMap.put("error", "数据库类型不存在");
                return resultMap;
            }
            generatorParam.setDbDriverClass(driverClassName);
            generatorParam.setDbConnectionURL(generatorParamDto.getDbConnectionURL().trim());
            generatorParam.setDbUserName(generatorParamDto.getDbUserName().trim());
            generatorParam.setDbPassword(generatorParamDto.getDbPassword().trim());
            List<TableParamDto> tableParamList = generatorParamDto.getTableParamList();
            if (tableParamList == null || tableParamList.size() == 0) {
                resultMap.put("error", "目标表不能为空");
                return resultMap;
            }
            // 生成文件地址
            String fileTargetSrc = getPath() + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyy-MM-dd")) + "/" + tableParamList.get(0).getModuleName() + DateTimeFormatter.ofPattern("HHmmss").format(LocalDateTime.now());
            resultMap.put("fileTargetSrc", fileTargetSrc);
            //当前时间
            String nowDateTime = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm").format(LocalDateTime.now());
            generatorParam.setNowDateTime(nowDateTime);
            for (TableParamDto tableParam : tableParamList) {
                GeneratorParam param = DBUtil.getTableInfo(tableParam.getTableName(), tableParam.getTableNamePrefix(), generatorParam);
                param.setModuleName(tableParam.getModuleName());
                Creator.create(param, fileTargetSrc, templateFilePath);
            }
        } catch (Exception e) {
            logger.error("生成失败，原因:", e);
            resultMap.put("error", e.getMessage());
            return resultMap;
        }
        resultMap.put("success", "代码生成成功");
        return resultMap;
    }

    @RequestMapping("/downloadZip")
    @ResponseBody
    public void downloadZip(String fileTargetSrc, HttpServletResponse response) {
        ZipUtil.downLoad(response, fileTargetSrc, fileTargetSrc.substring(fileTargetSrc.lastIndexOf('/') + 1));
    }


    /**
     * 获取jar包所在路径
     *
     * @return
     */
    public String getPath() {
        return "log" + "/";
    }
}
